package unicall.em.controllers;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import unicall.em.dtos.MediaDto;
import unicall.em.models.Media;
import unicall.em.models.vo.MediaQuery;
import unicall.em.services.MediaService;
import unicall.em.utils.AWSUtil;
import unicall.em.utils.Constant;
import unicall.em.utils.StringUtil;

@Controller
@RequestMapping(value = "/media")
public class Medias {
    
    @Autowired
    private MediaService mediaService;

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView index(@ModelAttribute("query") MediaQuery query,@RequestParam(required=false,value="pageNumber",defaultValue="0")int pageNumber) {
       ModelAndView mv = new ModelAndView();
       Page<Media> page = mediaService.findAll(query.toSpec(), new PageRequest(pageNumber,Constant.PAGE_SIZE));
       List<MediaDto> dataList = page.getContent().stream().map(e->e.toDto()).collect(Collectors.toList());
       mv.addObject("dataList",dataList);
       mv.addObject("page", page);
       mv.setViewName("/medias/index");
       return mv;
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(Model model) {
        model.addAttribute("media", new MediaDto());
        return "/medias/add";
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String create(@Valid @ModelAttribute("media") MediaDto media, BindingResult result) {
        if (result.hasErrors()) {
            return "/medias/add";
        } else {
            Media _media = mediaService.add(media);
            mediaService.upload(_media,media.getFileName());
            return "redirect:/media";
        }
    }

    @RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
    public String edit(@PathVariable("id") String id, Model model) {
        Media media = mediaService.findById(id);
        MediaDto dto = media.toDto();
        model.addAttribute("media", dto);
        return "/medias/edit";
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public String update(@PathVariable("id") String id,@Valid @ModelAttribute("media") MediaDto media,BindingResult result) {
        if(result.hasErrors()){
            return "/medias/edit";
        }else{
            Media _media = mediaService.findById(id);
            String oldFileName =StringUtil.trim(_media.getFileName());
            Media newMedia = mediaService.update(media);
            String newFileName =StringUtil.trim(newMedia.getFileName());
            if(!oldFileName.equals(newFileName)){
                mediaService.upload(newMedia, newFileName);
            }
            return "redirect:/media";
        }
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String show(@PathVariable("id") String id, Model model) {
        Media media = mediaService.findById(id);
        model.addAttribute("media", media.toDto());
        return "/medias/show";

    }

    /**
     * 语音文件删除
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public String destroy(@PathVariable("id") String id) {
        mediaService.deleteById(id);
        return "redirect:/media";
    }

    @ResponseBody
    @RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String upload(HttpServletRequest request,
            @RequestParam("uploadFile") MultipartFile uploadFile) {
        String bucketName = Constant.AWS_BUCKET_NAME; //需要与HELPDesk对接完成后调整
        //bucketName 格式：/uobject/tenantId(域名)/ucpaas/appId/ivr
        String nickName  = request.getParameter("nickName"); //别名
        String appId = request.getParameter("appId"); //appId;
        String dir = nickName+"/ucpaas/"+appId+"/ivr";
        String fileName = UUID.randomUUID().toString() + ".wav";
        boolean rcode = AWSUtil.uploadObject(bucketName,dir,fileName, uploadFile);
        Map<String, String> map = new HashMap<String, String>();
        map.put("rcode", rcode + "");
        map.put("fileName", fileName);
        ObjectMapper mapper = new ObjectMapper();
        String result = null;
        try {
            result = mapper.writeValueAsString(map);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

}
